<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="快手视频爬虫笔记1：初级, blog">
    <meta name="description" content="这是我的个人网站，欢迎来访">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>快手视频爬虫笔记1：初级 | 头号咸鱼</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

    <script>(function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/7b318e23.js","daovoice")</script>
    

<meta name="generator" content="Hexo 5.3.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="头号咸鱼" type="application/atom+xml">
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">头号咸鱼</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">头号咸鱼</div>
        <div class="logo-desc">
            
            这是我的个人网站，欢迎来访
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-ox2wqm.png')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">快手视频爬虫笔记1：初级</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E6%8E%A8%E8%8D%90/">
                                <span class="chip bg-color">推荐</span>
                            </a>
                        
                            <a href="/tags/%E5%BF%AB%E6%89%8B/">
                                <span class="chip bg-color">快手</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E7%88%AC%E8%99%AB/" class="post-category">
                                爬虫
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-03-16
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2021-03-16
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    5.9k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    25 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <blockquote>
<p>还是现在开始写笔记吧！现在写好截图，把自己探索的过程写出来。目前实现功能：输入快手主播id，可以获取主页所有视频地址</p>
</blockquote>
<h4 id="一、经历"><a href="#一、经历" class="headerlink" title="一、经历"></a>一、经历</h4><h4 id="1-起因"><a href="#1-起因" class="headerlink" title="1.起因"></a>1.起因</h4><ul>
<li>大一下学期，自己学完python，就开始学python爬虫，希望让编程语言有实际用处（太心急），然后入坑BeautifulSoup库，总是得到一个空列表，而且自己一开始想要爬取的网站时<strong>快手视频</strong>（不知天高地厚）。提取的是空列表，python数据结构都没有搞清楚用明白，我就搜关于快手视频爬虫博客。正好就有<strong>这样的博客</strong>，我刚开始的折腾是<strong>连原理也不知道</strong>，看到博客感觉还行就照这上面一步一步的做，比如装双系统、破解校园网等……结果坑定了我，而且看的博客是很多平台都几乎一样，搞在上面是为了吸引流量的。</li>
<li>那片博客是使用fidder抓包工具，我肯定不成功。我还想观察一下视频链接规律，其实看不出规律。然后这么一串字符肯定是什么加密的，然后又想学逆向工程，破解快手app（异想天开），我没有去学，没基础资料少不好学。</li>
</ul>
<h4 id="2-经过"><a href="#2-经过" class="headerlink" title="2.经过"></a>2.经过</h4><ul>
<li>然后我放了一段时间不甘心，在重新学习python爬虫，从基础开始学，先爬取一篇页面的小说，或者视频地址。这时候的我有了写基础，可以爬取<strong>单页面小说</strong>，但没什么意思，因为是单页面，那是我也不知道什么跨页面爬虫，还没有遇到lxml库筛选信息。</li>
<li>到大一暑假，又不甘心，也是先从基础开始。我可以在web页面找出视频地址，然后下载，open函数写入二进制文件什么的，然后配合GUI库（导入这个库的名字粗心写错了，都能入坑，以为是第三方库），我可以复制.mp4地址，然后输入下载到本地，清空输入框。这是为后面做准备的</li>
<li>这个时候随着我爬虫的深入，知道了动态页面AJAX技术，把视频页面打印出来，就视频链接那里少了，当时还不会用post方法，和get方法没有搞清楚，HTML文档树、父子节点都是模糊的概念，就这个时候用lxml库提取信息吧！</li>
<li>自己还是不信，都以为用爬虫框架scrapy就可以提取不到视频地址，就可以下载到了，最后还是不甘的相信了<strong>要爬虫，必须知道地址</strong>。然后知道了selenium模拟浏览器爬虫，<strong>可见皆可爬</strong>。</li>
<li>这里还入了不少坑，驱动安装还很顺利，然后要打开包含自己登录信息的浏览器窗口，筛选，页面切换等。切换到了详细视频界面我等了几秒，然后筛选信息，这样做都找不出来视频地址，还是视频地址地方没有。然后，一言不和，直接手动下载，用的是上面提到的那个图形界面，实际是为了加速手动下载而制作的，代码没有记录下来。</li>
<li>坚持了快一个月，最后有60多G<span class="github-emoji"><span>😢</span><img src="https://github.githubassets.com/images/icons/emoji/unicode/1f622.png?v8" aria-hidden="true" onerror="this.parent.classList.add('github-emoji-fallback')"></span>,当时也没什么好做的，就干这个了，后面一个月我把《王者荣耀》下载回来了，结束了自己的python学习，开始学习后端框架Django</li>
<li>后来的后来，我断断续续的学了django，HTML、CSS、JS，不是学的很好，没怎么练习。对web有一定的了解后，我想着自己做好网站后上面放一些什么内容（想得真远，网站还没做好）。放视频把，我其他的小网站容易获取视频地址，像一些视频爬取的学习教程，简单，静态页面直接筛选就可以了，这是没有去想着爬取快手视频，知道太难了。</li>
<li>当时我就在给kindle屯书，做个电子书网站可以。这个时候我爬取了<code>简阅</code>里面的电子书封面名字等信息，这个利用了cookie登录，发送post请求，还有存储到数据库，感觉自己的爬虫技术<strong>脱胎换骨</strong>了,然后我再去试试快手，模拟登录啥的，结果还是失败。</li>
<li>后来我让爬虫技术为我所用，爬取电子书网站下载电子书。使用selenium提取百度网盘文件，期间也试过快手，但是没报什么希望了。</li>
<li>然后在<strong>吾爱破解</strong>论坛上面看到了一篇原创帖子,地址：<a target="_blank" rel="noopener" href="https://www.52pojie.cn/forum.php?mod=viewthread&amp;tid=1151961">https://www.52pojie.cn/forum.php?mod=viewthread&amp;tid=1151961</a></li>
<li>这个<strong>原创帖子</strong>感觉很靠谱，而且还有人成功了的评论，但是有了评论失效，寻求解决办法等，我怀着激动的心情自己跑了一遍，结果没成功。我后悔自己煤油早点发现这个帖子，就差不多过了三四个月的样子。看代码也没有看懂</li>
<li>对了，我之前没有放弃快手爬虫，我搜到了一篇真正用fidder抓包工具成功的博客，我参考自己也成功了，但是每次都要去fiddle里面去复制拼接一下地址，每次只能下载十几条。到这个时候发现了爬取快手视频也没有什么的，我终于成功了，但没有达到自己预期的效果，到这里为止吧！因为看到了单个帖子是批量爬取主页视频，而且是通过没有用到fidder。</li>
<li>post和get以及添加的参数，是之后自己学Vue和django前后端分离项目的时候完全搞清楚的。</li>
<li>识别验证码不好搞，多线程先搞好单线程再说，ip代理需求还没有遇到</li>
</ul>
<h4 id="3-现在"><a href="#3-现在" class="headerlink" title="3.现在"></a>3.现在</h4><ul>
<li><p>2021.2.21，我把自己平板里面的python爬虫电子书消化整理一下，没有报什么希望，爬虫也就那个样子。在《从零开始学Python网络爬虫》看到post请求这一张，AXJA加载页面，刷新一下，有用的信息一般在<strong>Network的XHR</strong>下，我是了书上的简书地址，是的。然后我觉得可以试一下快手，因为自己之前发送post请求，响应了一大堆东西，不好找，即使找到了也是拼接的（fidder的影响），所以没去深究。</p>
</li>
<li><p>自己试了一下快手，看了这几条的有用信息，我擦竟然有视频地址。</p>
</li>
<li><p>再继续探索，往下滑动，会出现新的，请求名字是一样的，再看，里面包含的就是新加载出来的视频地址信息。<strong>当时就觉得这本书，就说了post后那些是有用的信息，就让我重新找到了方法</strong></p>
</li>
<li><p>然后开始这一天的快手爬虫吧！</p>
</li>
</ul>
<h4 id="二、探索步骤"><a href="#二、探索步骤" class="headerlink" title="二、探索步骤"></a>二、探索步骤</h4><blockquote>
<p>首先需要登录账号，这样才能获取cookie信息。</p>
</blockquote>
<h4 id="1-查看XHR下的筛选信息"><a href="#1-查看XHR下的筛选信息" class="headerlink" title="1.查看XHR下的筛选信息"></a>1.查看XHR下的筛选信息</h4><ul>
<li>进入一个用户的主页：<a target="_blank" rel="noopener" href="https://video.kuaishou.com/profile/3xsmpz9kqmb3s3m">https://video.kuaishou.com/profile/3xsmpz9kqmb3s3m</a></li>
<li>检查源代码，选中下面的选项，然后刷新一下就可以看到如下信息了</li>
</ul>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221213938.png"></p>
<h4 id="2-观察信息"><a href="#2-观察信息" class="headerlink" title="2.观察信息"></a>2.观察信息</h4><ul>
<li>查看如下选项，第一个post请求，返回的数据可能是<strong>用户主页信息</strong></li>
</ul>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221214455.png"></p>
<ul>
<li>然后查看一下其他的graphql的信息，有个是包含了<strong>视频信息</strong></li>
</ul>
<blockquote>
<p>如果没有，result是2，页面显示没有加载出视频，刷新几次成功出现视频后，就可以找到这条信息，result为1表示成功，后面要用到的。</p>
<p>其他的graphql也是相关的结构，但feeds的内容不是视频信息，继续找下去（相对很少哈）。如果你不下滑网页，就只有一个graphql包含视频信息。如果向下划出现的</p>
</blockquote>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221214807.png"></p>
<ul>
<li>这个是<strong>用户登录</strong>，自己先研究了一下才发现其他信息里面含有视频地址的。</li>
</ul>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221220740.png"></p>
<h4 id="3-使用Postman测试请求和代码实现"><a href="#3-使用Postman测试请求和代码实现" class="headerlink" title="3.使用Postman测试请求和代码实现"></a>3.使用Postman测试请求和代码实现</h4><h6 id="用户登录信息"><a href="#用户登录信息" class="headerlink" title="用户登录信息"></a>用户登录信息</h6><blockquote>
<p>这个对爬取视频地址没什么用，但自己先做了这件事情，也是一种练习,方法和后面的一样</p>
</blockquote>
<ol>
<li>观察头部信息</li>
</ol>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221222343.png"></p>
<blockquote>
<p>General包含状态信息，200表示成功，这里主要用到URL信息的值，是等下post请求发送的地址。</p>
<p>Response Headers是响应的返回的信息，暂时没用</p>
</blockquote>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221222659.png"></p>
<blockquote>
<p>Request Headers这个很重要，里面的一些信息是等下要填入的</p>
<p>Form Data这个也很重要，等下要用到</p>
</blockquote>
<ol start="2">
<li>postman填入信息</li>
</ol>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221222922.png"></p>
<blockquote>
<p>这里就是Request Headers中的键值对</p>
</blockquote>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221223035.png"></p>
<blockquote>
<p>还要填入这个，然后就可以了，点击发送</p>
</blockquote>
<ul>
<li>发送返回的信息，result为1，成功</li>
</ul>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221223139.png"></p>
<blockquote>
<p>然后下面的是浏览器返回的信息，是一致的。但是后面暂时用不上</p>
</blockquote>
<ol start="3">
<li>实现代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">
#登录
import requests

URL = "https://id.kuaishou.com/pass/kuaishou/login/passToken?sid=kuaishou.server.web"
headers = {
    "User-Agent":"PostmanRuntime/7.26.8",
    "Connection":"keep-alive",
    "Referer":"https://video.kuaishou.com/profile/3xcidpetejrcagy",
    "Cookie":r'clientid=3; did=web_d37f50afed8ef1a623554f109df9a6d7; client_key=65890b29; infra_kuaishou_oauth_state=e180905e1fbbddcc1be1b604802af970_{"sid":"kuaishou.live.web","callback":"","appId":"ks_live_qq","htmlJump":"https://live.kuaishou.com/thirdPart/qq/?callback=https%3A%2F%2Fvideo.kuaishou.com%2FthirdPart%2Fqq%2F&amp;followUrl=https://video.kuaishou.com/thirdPart/qq/","htmlJumpCallback":"","issueTime":1613883170}; userId=1297533855; userId=1297533855; passToken=ChNwYXNzcG9ydC5wYXNzLXRva2VuEpAB5c7daDCmfLJGUB6LQLgljXamVWAyIlVjCS-sNwqTRev4mfC7ClrmeLZb_rYe43GB_gAMkXVlil_zsdaSyVrCatOl1on2mnLE6lZU82SIqWD79YtdIWPINFyX_fAkgjDCF-wiIj4IYmH6-WtPxYsRVxYxanvgeaT-hidyo1P64s5r1gto11M922-s9MN8LGXUGhKg_o5KaBBN5LxbmRWQRwGOczwiIDuQz_USHjJc3GJ__awgbeUigA2uhCy_EjgckcVg24kvKAUwAQ',
    "Host":"id.kuaishou.com",
    "ORigin":"https://video.kuaishou.com"
}
params = {
    "sid":"kuaishou.server.web"
}

res = requests.post(URL,data=params,headers = headers)
print(res.text)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>输出的结果就是postman或者浏览器响应的返回结果。就是这样的流程。</p>
</blockquote>
<h6 id="视频信息"><a href="#视频信息" class="headerlink" title="视频信息"></a>视频信息</h6><blockquote>
<p>这里有个巨坑，绕了我半天，差点放弃了，幸好自己探索发现了。解决得很巧妙，直接说出来就少了乐趣，这样探索一番得出来这个简单的解决方法。</p>
</blockquote>
<ol>
<li>观察请求信息</li>
</ol>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221223930.png"></p>
<blockquote>
<p>其他的和上面方法一样，这里要注意 Request Payload信息。这是一个<strong>弃坑点</strong>，自己搜索博客就解决了，地址：<a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_31880681/article/details/112052799%E3%80%82%E8%BF%99%E7%AF%87%E5%8D%9A%E5%AE%A2%E5%86%99%E5%BE%97%E6%8E%92%E7%89%88%E4%B8%8D%E5%A5%BD%EF%BC%8C%E7%9C%8B%E8%B5%B7%E6%9D%A5%E8%B4%A8%E9%87%8F%E6%9C%89%E7%82%B9%E4%BD%8E%EF%BC%8C%E4%BD%86%E6%98%AF%E8%BF%99%E6%98%AF%E8%87%AA%E5%B7%B1%E7%9C%8B%E5%88%B0%E6%9C%80%E6%96%B0%E7%9A%84%E5%85%B3%E4%BA%8E%E5%BF%AB%E6%89%8B%E8%A7%86%E9%A2%91%E7%88%AC%E8%99%AB%E7%9A%84%EF%BC%8C2020.12.30%E3%80%82%E8%87%AA%E5%B7%B1%E6%B2%A1%E5%8E%BB%E8%AF%95%EF%BC%8C%E4%BD%86%E6%98%AF%E8%BF%99%E6%9D%A1%E4%BF%A1%E6%81%AF%E5%AF%B9%E6%88%91%E5%BE%88%E6%9C%89%E7%94%A8%EF%BC%8C%E5%B0%B1%E6%98%AF%E6%8A%8A">https://blog.csdn.net/weixin_31880681/article/details/112052799。这篇博客写得排版不好，看起来质量有点低，但是这是自己看到最新的关于快手视频爬虫的，2020.12.30。自己没去试，但是这条信息对我很有用，就是把</a> Request Payload信息如何添加到代码中。</p>
<p>还有篇博客教你怎么把这条信息添加到Postman中。</p>
</blockquote>
<ol start="2">
<li>添加Postman信息</li>
</ol>
<ul>
<li>添加头部信息</li>
</ul>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221224916.png"></p>
<ul>
<li>添加Request Payload信息</li>
</ul>
<blockquote>
<p>红色框的这个键值对一定要填上去，指定格式。然后选Body的raw，把信息复制粘贴到上面就可以了。</p>
</blockquote>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221225134.png"></p>
<ol start="3">
<li>测试</li>
</ol>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221225303.png"></p>
<ul>
<li><p>返回的body信息就是之前再浏览器中看到的<strong>视频信息</strong></p>
</li>
<li><p>如果连续点击太快，就会返回result的值为2，那就表示不成功，可能触发了<strong>反爬虫机制</strong>。所以写代码的时候要<strong>注意延时</strong>，可能是通过IP地址判断的、或者是cookie信息。然后你再发送，一直返回result为2.</p>
</li>
<li><p>该怎么办呢？去浏览器刷新用户界面，第一两次没有显示视频，知道显示视频，再到postman发送就可以了。（<strong>写博客的时候发现的</strong>，之前写代码的时候被坑可能就是这个原因）</p>
</li>
<li><p>先说说。写代码爬取<strong>有时候发送的result为2，有的时候报错，有的时候乱码</strong>。result为2就是请求太多次了，探索中无意间刷新了页面，然后输出乱码，可能再为2的基础上该错了编码。报错的原因是请求到了正则的数据，但是经过了加密br，解析不出来。</p>
</li>
</ul>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221225407.png"></p>
<ol start="4">
<li>实现代码没那么容易，遇到了上述情况</li>
</ol>
<h6 id="问题探索"><a href="#问题探索" class="headerlink" title="问题探索"></a>问题探索</h6><blockquote>
<p>就感觉很懵，Postman发送返回了想要的信息，而代码中就不行(这让我以为快手爬虫真的的没那么容易，就像之前自己请求的页面就是少了视频地址)，我重新对比了一下代码中填入的信息和psotman没错。然后出现了乱码，这给了我希望，至少可以改一下。然后报错，我就去搜json库的使用，查看数据类型。还有以为result为2的返回信息太短，视频信息可能包含在body里面，学习了request.json(),最后才知道这就是返回信息，为2代表错误。这时自己看到了之前再<strong>吾爱破解</strong>上面看到的帖子，发现和我的思路是一样的。</p>
</blockquote>
<ol>
<li>编码问题</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">v_json = json.loads(res.content.decode(encoding='utf-8'))
res.encoding = "utf-8"
change = json.loads(res.text)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<ul>
<li>这是我注释的代码。具体的去学习了json，decode函数和encode函数，还有res的encoding，编码GBK，二进制变为utf-8格式等，都没有成功。</li>
</ul>
<ol start="2">
<li>解决办法</li>
</ol>
<ul>
<li>我改来改去编码，一会好大多数情况坏，我就像可不可以从request的请求中查看响应数据的编码。</li>
<li>先看到返回信息这一项，然后复制搜索，看到这篇博客</li>
</ul>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221231952.png"></p>
<ul>
<li>博客地址：<a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_40414337/article/details/88561066">https://blog.csdn.net/weixin_40414337/article/details/88561066</a></li>
<li>自己<strong>没有感到高兴</strong>，想到，原来还是用来算法加密呀，自己想要破解还是要研究这个算法，还不知道能不能逆向破解（没细看博客的第一种方法，这也让我后来的解决办法使我更高兴），还是准备放弃把。</li>
<li>我看一下请求头，果然有相关的这一项</li>
</ul>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221232431.png"></p>
<ul>
<li>我抱着试一下的心态把代码中的br删除，结果成功了，真是意外的惊喜。问题解决了，返回的是result为1的视频信息。</li>
</ul>
<ol start="3">
<li>实现代码</li>
</ol>
<blockquote>
<p>这波代码，可以爬取到视频地址</p>
</blockquote>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"># -*- coding: utf-8 -*-

#请求mp4地址
import requests
import json
URL = "https://video.kuaishou.com/graphql"
headers = {
    "accept":"*/*",
    "Content-Length":"&lt;calculated when request is sent&gt;",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    "content-type": "application/json",
    "Cookie": r'kpf=PC_WEB; kpn=KUAISHOU_VISION; clientid=3; did=web_ec874916e390b9741609686125a0452e; ktrace-context=1|MS43NjQ1ODM2OTgyODY2OTgyLjQ4Njc5OTUxLjE2MTM4NzkxMTIzMjYuMTMwNTE=|MS43NjQ1ODM2OTgyODY2OTgyLjQ0MjY3MTM5LjE2MTM4NzkxMTIzMjYuMTMwNTI=|0|graphql-server|webservice|false|NA; didv=1613879531823; client_key=65890b29; userId=1297533855; kuaishou.server.web_st=ChZrdWFpc2hvdS5zZXJ2ZXIud2ViLnN0EqAB8Z5m3BRHrf-1v5Z3jYzDbxSqfZqPgXaAGNWqHToLvTcu2ffsQTHqvH7InOyZupwpWaD2VxNw_6AykWI_D6nDcoFNyV_pL1NQYIbsJALeodTtWBKBfrv1WjkricjHKic7pyounMCad2w0TYNrS9o7BHf74gT1qzeqmhn_vZqQmB-23EMXTs0oSfL1whX8fQT4B_x7iTCWMvo23tO2g5A9khoSS2UWrTnDahVDKzRYjzjLpJM-IiCoU-W2Fu2Q2zI5Pc5_wo-jO6UfYiI4nwe3SL756q5I6CgFMAE; kuaishou.server.web_ph=c122bcd35018850582631a616bdf84d2e6a7',
    "Host": "video.kuaishou.com",
    "Origin": "https://video.kuaishou.com",
    "Referer": "https://video.kuaishou.com/profile/3xcidpetejrcagy",
    "User-Agent": "PostmanRuntime/7.26.8"
}
payload = {"operationName":"visionProfilePhotoList","variables":{"userId":"3xcidpetejrcagy","pcursor":"","page":"profile"},"query":"query visionProfilePhotoList($pcursor: String, $userId: String, $page: String, $webPageArea: String) {\n  visionProfilePhotoList(pcursor: $pcursor, userId: $userId, page: $page, webPageArea: $webPageArea) {\n    result\n    llsid\n    webPageArea\n    feeds {\n      type\n      author {\n        id\n        name\n        following\n        headerUrl\n        headerUrls {\n          cdn\n          url\n          __typename\n        }\n        __typename\n      }\n      tags {\n        type\n        name\n        __typename\n      }\n      photo {\n        id\n        duration\n        caption\n        likeCount\n        realLikeCount\n        coverUrl\n        coverUrls {\n          cdn\n          url\n          __typename\n        }\n        photoUrls {\n          cdn\n          url\n          __typename\n        }\n        photoUrl\n        liked\n        timestamp\n        expTag\n        animatedCoverUrl\n        __typename\n      }\n      canAddComment\n      currentPcursor\n      llsid\n      status\n      __typename\n    }\n    hostName\n    pcursor\n    __typename\n  }\n}\n"}

def get_data():
    res = requests.post(URL, headers=headers, json=payload)
    res.encoding="utf-8"
    m_json = res.json()  #字典格式
    status = m_json["data"]["visionProfilePhotoList"]["result"]
    feeds_list = m_json["data"]["visionProfilePhotoList"]["feeds"]
    for mp4_dict in feeds_list:
        mp4_url = mp4_dict["photo"]["photoUrl"]
        print(mp4_url)
get_data()<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221193129.png"></p>
<h6 id="获取页面全部视频"><a href="#获取页面全部视频" class="headerlink" title="获取页面全部视频"></a>获取页面全部视频</h6><blockquote>
<p>可以筛选出一个post请求响应信息的全部视频地址，要怎么获取整个页面的所有视频地址呢？</p>
</blockquote>
<ol>
<li>观察多条post请求信息</li>
</ol>
<ul>
<li>头部信息没什么不同的，Request Payload信息有所不同</li>
<li>第一个pcursor的值为空，</li>
</ul>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221233536.png"></p>
<ul>
<li>其他的有个值</li>
</ul>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221233806.png"></p>
<ul>
<li>这个可能是游标的位置，越往下这个值越小</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">这个可能是游标位置，越往下越来越小
1.598342291229E12
1.590398863672E12
1.582021160207E12
1.565928253173E12
1.538118890965E12	#这个是最底下的，尝试如果比这还小请求的数据<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>这个变化不好掌控，自己看一下和我思路一样吾爱破解的那片帖子，也是通过pcurosor来获取其他请求信息的，但是自己没看懂，自己确定一个值又不好确定，最小是多少？</li>
</ul>
<ol start="2">
<li>pcursor值的探索</li>
</ol>
<ul>
<li>我观察到第一次请求响应的信息里面包含了pcursor的值，那么就把第一次这个值保留下来添加到下一次的payload中，依次循环</li>
</ul>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221234433.png"></p>
<ul>
<li>我把视频的摘要信息添加进去，依次来辨别视频是否相同。先这使用了2次函数，两次的视频信息确实不一样，成功</li>
</ul>
<ol start="3">
<li>什么时候到底</li>
</ol>
<ul>
<li>那么我找个视频较少的主页，多执几次函数，看看最后的返回结果</li>
</ul>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210221235138.png"></p>
<ul>
<li>最后返回了no_more参数，可以次来结束。再吾爱破解那帖子中也看到过使用这参数，这样做为了验证一下。</li>
</ul>
<ol start="4">
<li>实现代码</li>
</ol>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"># -*- coding: utf-8 -*-

#请求mp4地址
import requests
import json
URL = "https://video.kuaishou.com/graphql"
headers = {
    "accept":"*/*",
    "Content-Length":"&lt;calculated when request is sent&gt;",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    "content-type": "application/json",
    "Cookie": r'kpf=PC_WEB; kpn=KUAISHOU_VISION; clientid=3; did=web_ec874916e390b9741609686125a0452e; ktrace-context=1|MS43NjQ1ODM2OTgyODY2OTgyLjQ4Njc5OTUxLjE2MTM4NzkxMTIzMjYuMTMwNTE=|MS43NjQ1ODM2OTgyODY2OTgyLjQ0MjY3MTM5LjE2MTM4NzkxMTIzMjYuMTMwNTI=|0|graphql-server|webservice|false|NA; didv=1613879531823; client_key=65890b29; userId=1297533855; kuaishou.server.web_st=ChZrdWFpc2hvdS5zZXJ2ZXIud2ViLnN0EqAB8Z5m3BRHrf-1v5Z3jYzDbxSqfZqPgXaAGNWqHToLvTcu2ffsQTHqvH7InOyZupwpWaD2VxNw_6AykWI_D6nDcoFNyV_pL1NQYIbsJALeodTtWBKBfrv1WjkricjHKic7pyounMCad2w0TYNrS9o7BHf74gT1qzeqmhn_vZqQmB-23EMXTs0oSfL1whX8fQT4B_x7iTCWMvo23tO2g5A9khoSS2UWrTnDahVDKzRYjzjLpJM-IiCoU-W2Fu2Q2zI5Pc5_wo-jO6UfYiI4nwe3SL756q5I6CgFMAE; kuaishou.server.web_ph=c122bcd35018850582631a616bdf84d2e6a7',
    "Host": "video.kuaishou.com",
    "Origin": "https://video.kuaishou.com",
    "Referer": "https://video.kuaishou.com/profile/3xcidpetejrcagy",
    "User-Agent": "PostmanRuntime/7.26.8"
}
payload = {"operationName":"visionProfilePhotoList","variables":{"userId":"3xcidpetejrcagy","pcursor":"","page":"profile"},"query":"query visionProfilePhotoList($pcursor: String, $userId: String, $page: String, $webPageArea: String) {\n  visionProfilePhotoList(pcursor: $pcursor, userId: $userId, page: $page, webPageArea: $webPageArea) {\n    result\n    llsid\n    webPageArea\n    feeds {\n      type\n      author {\n        id\n        name\n        following\n        headerUrl\n        headerUrls {\n          cdn\n          url\n          __typename\n        }\n        __typename\n      }\n      tags {\n        type\n        name\n        __typename\n      }\n      photo {\n        id\n        duration\n        caption\n        likeCount\n        realLikeCount\n        coverUrl\n        coverUrls {\n          cdn\n          url\n          __typename\n        }\n        photoUrls {\n          cdn\n          url\n          __typename\n        }\n        photoUrl\n        liked\n        timestamp\n        expTag\n        animatedCoverUrl\n        __typename\n      }\n      canAddComment\n      currentPcursor\n      llsid\n      status\n      __typename\n    }\n    hostName\n    pcursor\n    __typename\n  }\n}\n"}

def get_data():
    res = requests.post(URL, headers=headers, json=payload)
    res.encoding="utf-8"
    m_json = res.json()  #字典格式
    status = m_json["data"]["visionProfilePhotoList"]["result"]
    feeds_list = m_json["data"]["visionProfilePhotoList"]["feeds"]
    pcursor = m_json["data"]["visionProfilePhotoList"]["pcursor"]
    #第一次返回的pcursor值添加到  payload ,观察结果是否不一样
    #确实不一样，选个作品少的 多运行几次
    payload["variables"]["pcursor"]=pcursor
    
    print(pcursor)
    print("---------------------------------------------------------------------------------------------------------------")
    for mp4_dict in feeds_list:
        mp4_url = mp4_dict["photo"]["photoUrl"]
        caption = mp4_dict["photo"]["caption"]
        print(caption)
        #print(mp4_url)
#第一次
get_data()
#第二次
get_data()
get_data()
get_data()<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>最终代码注意延时</p>
</blockquote>
<h4 id="4-一些下载方式代码"><a href="#4-一些下载方式代码" class="headerlink" title="4.一些下载方式代码"></a>4.一些下载方式代码</h4><blockquote>
<p>这是进一步代码的编写，自己写代码过程中写的，可能有点乱。</p>
</blockquote>
<ul>
<li>这样的话就实现了将整个主页视频存储到列表MP4URL中</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none"># -*- coding: utf-8 -*-

#请求mp4地址
import requests
import json

URL = "https://video.kuaishou.com/graphql"

headers = {
    "accept":"*/*",
    "Content-Length":"&lt;calculated when request is sent&gt;",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    "content-type": "application/json",
    "Cookie": r'kpf=PC_WEB; kpn=KUAISHOU_VISION; clientid=3; did=web_d37f50afed8ef1a623554f109df9a6d7; client_key=65890b29; userId=1297533855; kuaishou.server.web_st=ChZrdWFpc2hvdS5zZXJ2ZXIud2ViLnN0EqABWJCSboNFaY05jQVekJIsYsazOBv3CwBFLOGTNWrZ4K7ITJMFqQ66A-IT3l7pMCP6w70iP7bU8dmitpRSfhHV2Tr4kyX0Pb6BjuRWz_nEpwMsvTNDooPoEboKnDZ2nSXZtW3gpKvCCezOoS3tFOyURZTaHt-GhtsnOUXRl_CfmIfp6Y1l7nEom8l1x6PJjUg9FooszHgJqIxigYfarOzTmhoSWXnZQFypWC8Fi7687FtZGgfDIiC4Pvu-LV02AKfQGWo_VGfUEcpMvcsNYTRPKOVc88Gd3SgFMAE; kuaishou.server.web_ph=9ef48347a0bb59b0abc7c977227df998333d',
    "Host": "video.kuaishou.com",
    "Origin": "https://video.kuaishou.com",
    "Referer": "https://video.kuaishou.com/profile/3xcidpetejrcagy",
    "User-Agent": "PostmanRuntime/7.26.8"
}

payload = {"operationName":"visionProfilePhotoList","variables":{"userId":"3xcidpetejrcagy","pcursor":"","page":"profile"},"query":"query visionProfilePhotoList($pcursor: String, $userId: String, $page: String, $webPageArea: String) {\n  visionProfilePhotoList(pcursor: $pcursor, userId: $userId, page: $page, webPageArea: $webPageArea) {\n    result\n    llsid\n    webPageArea\n    feeds {\n      type\n      author {\n        id\n        name\n        following\n        headerUrl\n        headerUrls {\n          cdn\n          url\n          __typename\n        }\n        __typename\n      }\n      tags {\n        type\n        name\n        __typename\n      }\n      photo {\n        id\n        duration\n        caption\n        likeCount\n        realLikeCount\n        coverUrl\n        coverUrls {\n          cdn\n          url\n          __typename\n        }\n        photoUrls {\n          cdn\n          url\n          __typename\n        }\n        photoUrl\n        liked\n        timestamp\n        expTag\n        animatedCoverUrl\n        __typename\n      }\n      canAddComment\n      currentPcursor\n      llsid\n      status\n      __typename\n    }\n    hostName\n    pcursor\n    __typename\n  }\n}\n"}
MP4URL = []

def get_data():

    res = requests.post(URL, headers=headers, json=payload)
    res.encoding="utf-8"
    m_json = res.json()  #字典格式
    feeds_list = m_json["data"]["visionProfilePhotoList"]["feeds"]
    pcursor = m_json["data"]["visionProfilePhotoList"]["pcursor"]
    payload["variables"]["pcursor"]=pcursor
    for mp4_dict in feeds_list:
        mp4_url = mp4_dict["photo"]["photoUrl"]
        MP4URL.append(mp4_url)
        print(mp4_url)
    print(pcursor)
    if pcursor=="no_more":
        return 0
    print("-----------------------------")
            
    

        
if __name__=='__main__':
    while(1):
        temp = get_data()
        if temp == 0:
            break
    print("---------------------程序结束-------------------")
    print(MP4URL)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>下载单条视频</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">def download_mp4():
    url = "https://txmov2.a.yximgs.com/upic/2021/02/21/17/BMjAyMTAyMjExNzIxNDBfMjQ0NzAyMDZfNDQ3NjYyNjMwNjhfMV8z_b_B5641b5296a602cb70e805ba49cfe96c2.mp4?tag=1-1613952672-xpcwebprofile-0-ff9xhc5mzz-0dfbcf5ed5eec2fa&amp;clientCacheKey=3xpjmw5bwu5bcyw_b.mp4&amp;tt=b&amp;di=7abc93c3&amp;bp=14734"
    res2 = requests.get(url)
    f = open("/home/test3.mp4","wb+")
    f.write(res2.content)
    f.close()<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>些代码实现了下载一个用户的所有视频，以用户名字创建文件夹，序号+视频Id号创建视频文件</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none"># -*- coding: utf-8 -*-

#请求mp4地址
import requests
import json
import os
URL = "https://video.kuaishou.com/graphql"

headers = {
    "accept":"*/*",
    "Content-Length":"&lt;calculated when request is sent&gt;",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    "content-type": "application/json",
    "Cookie": r'kpf=PC_WEB; kpn=KUAISHOU_VISION; clientid=3; did=web_d37f50afed8ef1a623554f109df9a6d7; client_key=65890b29; userId=1297533855; kuaishou.server.web_st=ChZrdWFpc2hvdS5zZXJ2ZXIud2ViLnN0EqABWJCSboNFaY05jQVekJIsYsazOBv3CwBFLOGTNWrZ4K7ITJMFqQ66A-IT3l7pMCP6w70iP7bU8dmitpRSfhHV2Tr4kyX0Pb6BjuRWz_nEpwMsvTNDooPoEboKnDZ2nSXZtW3gpKvCCezOoS3tFOyURZTaHt-GhtsnOUXRl_CfmIfp6Y1l7nEom8l1x6PJjUg9FooszHgJqIxigYfarOzTmhoSWXnZQFypWC8Fi7687FtZGgfDIiC4Pvu-LV02AKfQGWo_VGfUEcpMvcsNYTRPKOVc88Gd3SgFMAE; kuaishou.server.web_ph=9ef48347a0bb59b0abc7c977227df998333d',
    "Host": "video.kuaishou.com",
    "Origin": "https://video.kuaishou.com",
    "Referer": "https://video.kuaishou.com/profile/3xcidpetejrcagy",
    "User-Agent": "PostmanRuntime/7.26.8"
}

payload = {"operationName":"visionProfilePhotoList","variables":{"userId":"3xcidpetejrcagy","pcursor":"","page":"profile"},"query":"query visionProfilePhotoList($pcursor: String, $userId: String, $page: String, $webPageArea: String) {\n  visionProfilePhotoList(pcursor: $pcursor, userId: $userId, page: $page, webPageArea: $webPageArea) {\n    result\n    llsid\n    webPageArea\n    feeds {\n      type\n      author {\n        id\n        name\n        following\n        headerUrl\n        headerUrls {\n          cdn\n          url\n          __typename\n        }\n        __typename\n      }\n      tags {\n        type\n        name\n        __typename\n      }\n      photo {\n        id\n        duration\n        caption\n        likeCount\n        realLikeCount\n        coverUrl\n        coverUrls {\n          cdn\n          url\n          __typename\n        }\n        photoUrls {\n          cdn\n          url\n          __typename\n        }\n        photoUrl\n        liked\n        timestamp\n        expTag\n        animatedCoverUrl\n        __typename\n      }\n      canAddComment\n      currentPcursor\n      llsid\n      status\n      __typename\n    }\n    hostName\n    pcursor\n    __typename\n  }\n}\n"}
MP4URL = []
MP4ID = []
otherData = {}
# CAPTION = []
def get_data():

    res = requests.post(URL, headers=headers, json=payload)
    res.encoding="utf-8"
    m_json = res.json()  #字典格式
    feeds_list = m_json["data"]["visionProfilePhotoList"]["feeds"]
    pcursor = m_json["data"]["visionProfilePhotoList"]["pcursor"]
    
    
    
    payload["variables"]["pcursor"]=pcursor
    for mp4_dict in feeds_list:
        mp4_url = mp4_dict["photo"]["photoUrl"]
        MP4URL.append(mp4_url)
        
        mp4_id = mp4_dict["photo"]["id"]
        MP4ID.append(mp4_id)
        
#         caption= mp4_dict["photo"]["caption"]
#         CAPTION.append(caption)
        otherData["author"] = mp4_dict["author"]["name"]
        
        #print(mp4_url)
    print(pcursor)
    if pcursor=="no_more":
        return 0
    print("-----------------------------")
            
    
def download_mp4():
    result = dict(zip(MP4ID,MP4URL))
    if not os.path.exists("/home/data/%s"%(otherData["author"])):
        os.mkdir("/home/data/%s"%(otherData["author"]))
        
    i = 1000
    j = 0
    for key,value in result.items():
        i += 1
        res2 = requests.get(value)
        key = str(i)+"+++"+key
        path = "/home/data/%s/%s.mp4"%(otherData["author"],key)
        f = open(path,"wb")
        f.write(res2.content)
        f.close()
        
        j += 1

    
    
        
if __name__=='__main__':
    while(1):
        temp = get_data()
        if temp == 0:
            break
    print("---------------------程序结束-------------------")
    download_mp4()
    print(MP4URL)<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><img src="https://gitee.com/liangxinixn/blog002/raw/master/image01/20210222095352.png"></p>
<ul>
<li>多用户下载</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none"># -*- coding: utf-8 -*-

#请求mp4地址
import requests
import json
import os
URL = "https://video.kuaishou.com/graphql"

headers = {
    "accept":"*/*",
    "Content-Length":"&lt;calculated when request is sent&gt;",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    "content-type": "application/json",
    "Cookie": r'kpf=PC_WEB; kpn=KUAISHOU_VISION; clientid=3; did=web_d37f50afed8ef1a623554f109df9a6d7; client_key=65890b29; userId=1297533855; kuaishou.server.web_st=ChZrdWFpc2hvdS5zZXJ2ZXIud2ViLnN0EqABWJCSboNFaY05jQVekJIsYsazOBv3CwBFLOGTNWrZ4K7ITJMFqQ66A-IT3l7pMCP6w70iP7bU8dmitpRSfhHV2Tr4kyX0Pb6BjuRWz_nEpwMsvTNDooPoEboKnDZ2nSXZtW3gpKvCCezOoS3tFOyURZTaHt-GhtsnOUXRl_CfmIfp6Y1l7nEom8l1x6PJjUg9FooszHgJqIxigYfarOzTmhoSWXnZQFypWC8Fi7687FtZGgfDIiC4Pvu-LV02AKfQGWo_VGfUEcpMvcsNYTRPKOVc88Gd3SgFMAE; kuaishou.server.web_ph=9ef48347a0bb59b0abc7c977227df998333d',
    "Host": "video.kuaishou.com",
    "Origin": "https://video.kuaishou.com",
    "Referer": "https://video.kuaishou.com/profile/3xcidpetejrcagy",
    "User-Agent": "PostmanRuntime/7.26.8"
}

payload = {"operationName":"visionProfilePhotoList","variables":{"userId":"3xcidpetejrcagy","pcursor":"","page":"profile"},"query":"query visionProfilePhotoList($pcursor: String, $userId: String, $page: String, $webPageArea: String) {\n  visionProfilePhotoList(pcursor: $pcursor, userId: $userId, page: $page, webPageArea: $webPageArea) {\n    result\n    llsid\n    webPageArea\n    feeds {\n      type\n      author {\n        id\n        name\n        following\n        headerUrl\n        headerUrls {\n          cdn\n          url\n          __typename\n        }\n        __typename\n      }\n      tags {\n        type\n        name\n        __typename\n      }\n      photo {\n        id\n        duration\n        caption\n        likeCount\n        realLikeCount\n        coverUrl\n        coverUrls {\n          cdn\n          url\n          __typename\n        }\n        photoUrls {\n          cdn\n          url\n          __typename\n        }\n        photoUrl\n        liked\n        timestamp\n        expTag\n        animatedCoverUrl\n        __typename\n      }\n      canAddComment\n      currentPcursor\n      llsid\n      status\n      __typename\n    }\n    hostName\n    pcursor\n    __typename\n  }\n}\n"}
MP4URL = []
MP4ID = []
otherData = {}
# CAPTION = []
def get_data():

    res = requests.post(URL, headers=headers, json=payload)
    res.encoding="utf-8"
    m_json = res.json()  #字典格式
    print(m_json["data"]["visionProfilePhotoList"]["result"])
    feeds_list = m_json["data"]["visionProfilePhotoList"]["feeds"]
    pcursor = m_json["data"]["visionProfilePhotoList"]["pcursor"]
    
    
    
    payload["variables"]["pcursor"]=pcursor
    for mp4_dict in feeds_list:
        mp4_url = mp4_dict["photo"]["photoUrl"]
        MP4URL.append(mp4_url)
        
        mp4_id = mp4_dict["photo"]["id"]
        MP4ID.append(mp4_id)
        
#         caption= mp4_dict["photo"]["caption"]
#         CAPTION.append(caption)
        otherData["author"] = mp4_dict["author"]["name"]
        
        #print(mp4_url)
    print(pcursor)
    if pcursor=="no_more":
        return 0
    print("-----------------------------")
            
    
def download_mp4():
    result = dict(zip(MP4ID,MP4URL))
    if not os.path.exists("/home/data/%s"%(otherData["author"])):
        os.mkdir("/home/data/%s"%(otherData["author"]))
        
    i = 1000
    j = 0
    for key,value in result.items():
        i += 1
        res2 = requests.get(value)
        key = str(i)+"+++"+key
        path = "/home/data/%s/%s.mp4"%(otherData["author"],key)
        f = open(path,"wb")
        f.write(res2.content)
        f.close()
        
        j += 1

    

        
if __name__=='__main__':
    userList = ["3xcidpetejrcagy","3xsmpz9kqmb3s3m"]
    for userId in userList:
        payload["variables"]["userId"] = userId
        while(1):
            temp = get_data()
            if temp == 0:
                break
        print("---------------------当前用户地址完成-------------------")
        download_mp4()
        print("---------------------当前用户下载完成-------------------")
        payload["variables"]["pcursor"]=""<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h2 id="三、总结"><a href="#三、总结" class="headerlink" title="三、总结"></a>三、总结</h2><ul>
<li>本来自己向写完了再写博客的，觉得自己还没有做出来，还有存储什么的，连个数据库，配个GUI等。但是写到这里感觉自己好像<strong>干完</strong>一件大事一样，完了。</li>
<li>不多说了，还是进一步封装起来再说吧！那个headers中的cookie可能会过期，具体时间自己还不知道。还是赶紧爬了吧，不知道还会出什么反爬机制。<strong>虽然这个期待的结果没什么用，但是这个过程中自己提升了很多。</strong></li>
</ul>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">lxx</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://xinxinliang.github.io/2021/03/16/kuai-shou-shi-pin-pa-chong-bi-ji-yi-chu-ji/">http://xinxinliang.github.io/2021/03/16/kuai-shou-shi-pin-pa-chong-bi-ji-yi-chu-ji/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">lxx</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E6%8E%A8%E8%8D%90/">
                                    <span class="chip bg-color">推荐</span>
                                </a>
                            
                                <a href="/tags/%E5%BF%AB%E6%89%8B/">
                                    <span class="chip bg-color">快手</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="https://gitee.com/liangxinixn/guitar/raw/master/image01/20200726220206.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="https://gitee.com/liangxinixn/guitar/raw/master/image01/20200726220308.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2021/03/16/kuai-shou-shi-pin-pa-chong-bi-ji-wan/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-q6m1ol.png" class="responsive-img" alt="快手视频爬虫笔记(完)">
                        
                        <span class="card-title">快手视频爬虫笔记(完)</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-03-16
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%88%AC%E8%99%AB/" class="post-category">
                                    爬虫
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E8%AE%B0%E5%BD%95/">
                        <span class="chip bg-color">记录</span>
                    </a>
                    
                    <a href="/tags/%E5%BF%AB%E6%89%8B/">
                        <span class="chip bg-color">快手</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2021/03/15/ji-qi-xue-xi-suan-fa-wan-zhi-chi-xiang-liang-ji-svm/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-odlp9m.jpg" class="responsive-img" alt="机器学习算法（完）：支持向量机SVM">
                        
                        <span class="card-title">机器学习算法（完）：支持向量机SVM</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-03-15
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/" class="post-category">
                                    机器学习
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                    <a href="/tags/%E6%B0%B4/">
                        <span class="chip bg-color">水</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 头号咸鱼<br />'
            + '文章作者: lxx<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021</span>
            
            <span id="year">2021</span>
            <a href="/about" target="_blank">lxx</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">272.8k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/xinxinliang" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1974733812@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1974733812" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1974733812" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    
    <script>
        (function (i, s, o, g, r, a, m) {
            i["DaoVoiceObject"] = r;
            i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date();
            a = s.createElement(o), m = s.getElementsByTagName(o)[0];
            a.async = 1;
            a.src = g;
            a.charset = "utf-8";
            m.parentNode.insertBefore(a, m)
        })(window, document, "script", ('https:' == document.location.protocol ? 'https:' : 'http:') +
            "//widget.daovoice.io/widget/6984b559.js", "daovoice")
        daovoice('init', {
            app_id: "7b318e23"
        });
        daovoice('update');
    </script>
    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
